import { useState, useRef, useEffect } from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls, useGLTF, Html } from '@react-three/drei';
import * as THREE from 'three';
import { useTranslation } from 'react-i18next';

// 艺术品接口
interface Artwork {
  id: string;
  position: [number, number, number];
  title: string;
  author: string;
  description: string;
  type: string;
}

// 导航箭头接口
interface NavigationArrow {
  id: string;
  position: [number, number, number];
  targetPosition: [number, number, number];
  label: string;
  direction: string;
  distance: string; // 添加距离信息
  action?: 'navigate' | 'enterHouse' | 'exitHouse'; // 添加动作类型
}

// 艺术品组件（显示为3D标记）
function ArtworkMarker({ artwork, onSelect }: { artwork: Artwork; onSelect: (art: Artwork) => void }) {
  const [hovered, setHovered] = useState(false);
  
  return (
    <mesh
      position={artwork.position}
      onClick={() => onSelect(artwork)}
      onPointerOver={() => setHovered(true)}
      onPointerOut={() => setHovered(false)}
      scale={hovered ? 1.2 : 1}
    >
      <sphereGeometry args={[0.3, 32, 32]} />
      <meshStandardMaterial 
        color={hovered ? "#ffd700" : "#ff6b6b"} 
        emissive={hovered ? "#ffd700" : "#ff6b6b"}
        emissiveIntensity={hovered ? 0.3 : 0.1}
      />
      <Html distanceFactor={8}>
        <div style={{ 
          color: 'white', 
          background: 'rgba(0,0,0,0.8)', 
          padding: '6px 10px', 
          borderRadius: '6px',
          fontSize: '12px',
          fontWeight: 'bold',
          border: '2px solid gold',
          boxShadow: '0 4px 8px rgba(0,0,0,0.3)',
          marginTop: '8px'
        }}>
          🎯 {artwork.title}
        </div>
      </Html>
    </mesh>
  );
}

// 平面箭头组件（像图片中的样式）
function NavigationArrow({ arrow, onNavigate, onEnterHouse }: { 
  arrow: NavigationArrow; 
  onNavigate: (target: [number, number, number]) => void;
  onEnterHouse?: () => void;
}) {
  const [hovered, setHovered] = useState(false);

  const handleClick = () => {
    if (arrow.action === 'enterHouse' && onEnterHouse) {
      onEnterHouse();
    } else {
      onNavigate(arrow.targetPosition);
    }
  };

  return (
    <group position={arrow.position}>
      {/* 平面箭头（贴在地面最下面） */}
      {/* →符号箭头 */}
      <Html distanceFactor={6} position={[0, 0.5, 0]}>
        <div 
          onClick={handleClick}
          onMouseOver={() => setHovered(true)}
          onMouseOut={() => setHovered(false)}
          style={{
            fontSize: hovered ? '32px' : '28px',
            color: arrow.action === 'enterHouse' ? (hovered ? '#ff00ff' : '#ff6600') : (hovered ? '#00ff00' : '#ffffff'),
            fontWeight: 'bold',
            cursor: 'pointer',
            textShadow: '2px 2px 4px rgba(0,0,0,0.8)',
            transition: 'all 0.3s ease',
            transform: hovered ? 'scale(1.2)' : 'scale(1)',
            userSelect: 'none'
          }}
        >
          {arrow.action === 'enterHouse' ? '🏠' : '→'}
        </div>
      </Html>
      
      {/* 距离标签 */}
      <Html distanceFactor={8} position={[0, 1, 0]}>
        <div style={{ 
          color: 'white', 
          background: arrow.action === 'enterHouse' ? 'rgba(255,102,0,0.9)' : 'rgba(0,0,0,0.9)', 
          padding: '8px 16px', 
          borderRadius: '10px',
          fontSize: '14px',
          fontWeight: 'bold',
          border: arrow.action === 'enterHouse' ? '2px solid #ff6600' : '2px solid #ff0000',
          boxShadow: '0 4px 12px rgba(0,0,0,0.6)',
          textAlign: 'center',
          minWidth: '100px'
        }}>
          {arrow.label}<br/>
          <span style={{ color: '#ffaa00', fontSize: '12px' }}>{arrow.distance}</span>
        </div>
      </Html>
    </group>
  );
}

// 详情面板
function DetailsPanel({ artwork, onClose }: { artwork: Artwork | null; onClose: () => void }) {
  const { t } = useTranslation();
  if (!artwork) return null;
  return (
    <div style={{
      position: 'absolute',
      top: '20px',
      right: '20px',
      background: 'linear-gradient(135deg, rgba(0,0,0,0.9) 0%, rgba(20,20,20,0.9) 100%)',
      color: 'white',
      padding: '25px',
      borderRadius: '15px',
      width: '350px',
      zIndex: 1,
      border: '2px solid gold',
      boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
      backdropFilter: 'blur(10px)'
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px' }}>
        <h2 style={{ margin: 0, fontSize: '24px', color: '#ffd700' }}>{artwork.title}</h2>
        <button 
          onClick={onClose} 
      style={{
            background: '#ff4444', 
            color: 'white', 
            border: 'none', 
            borderRadius: '50%', 
            width: '30px', 
            height: '30px', 
            cursor: 'pointer',
            fontSize: '16px',
            fontWeight: 'bold'
          }}
        >
          ×
        </button>
      </div>
      <div style={{ marginBottom: '15px' }}>
        <p style={{ margin: '8px 0', fontSize: '16px', color: '#ccc' }}>
          <strong style={{ color: '#ffd700' }}>{t('sd.details.type')}</strong>{artwork.type}
        </p>
        <p style={{ margin: '8px 0', fontSize: '16px', color: '#ccc' }}>
          <strong style={{ color: '#ffd700' }}>{t('sd.details.author')}</strong>{artwork.author}
        </p>
      </div>
      <div style={{ 
        background: 'rgba(255,215,0,0.1)', 
        padding: '15px', 
        borderRadius: '10px', 
        border: '1px solid rgba(255,215,0,0.3)' 
      }}>
        <p style={{ margin: 0, lineHeight: '1.6', fontSize: '14px' }}>
          {artwork.description}
        </p>
      </div>
    </div>
  );
}

// 展览馆模型
function ExhibitionHall() {
  const { scene } = useGLTF('/7d.glb'); // 使用7d.glb模型
  return <primitive object={scene} scale={1} position={[0, 0, 0]} rotation={[0, 0, 0]} />;
}

// 房子内部模型
function HouseInterior() {
  const { scene } = useGLTF('/3d4.glb'); // 使用3d3.glb模型
  return <primitive object={scene} scale={1} position={[0, 0, 0]} rotation={[0, 0, 0]} />;
}

// 房子内部导航点组件
function HouseInteriorMarker({ position, onEnterDeep }: { 
  position: [number, number, number]; 
  onEnterDeep: () => void; 
}) {
  const { t } = useTranslation();
  return (
    <mesh position={position} onClick={onEnterDeep}>
      <sphereGeometry args={[0.3, 16, 16]} />
      <meshStandardMaterial color="#ff6b6b" emissive="#ff3333" emissiveIntensity={0.3} />
      <Html distanceFactor={10}>
        <div style={{
          background: 'rgba(255, 107, 107, 0.9)',
          color: 'white',
          padding: '8px 12px',
          borderRadius: '8px',
          fontSize: '14px',
          fontWeight: 'bold',
          cursor: 'pointer',
          border: '2px solid #ff3333',
          boxShadow: '0 4px 8px rgba(0,0,0,0.3)',
          transform: 'translate(-50%, -120%)',
          whiteSpace: 'nowrap'
        }}>
          🚪 {t('sd.house.enterDeep')}
        </div>
      </Html>
    </mesh>
  );
}

// 房子深层内部模型
function HouseDeepInterior() {
  const { scene } = useGLTF('/3d2.glb'); // 使用3d2.glb作为深层内部
  return <primitive object={scene} scale={0.8} position={[0, -1, 0]} rotation={[0, Math.PI, 0]} />;
}

function Sd() {
  const { t } = useTranslation();
  const [selectedArtwork, setSelectedArtwork] = useState<Artwork | null>(null);
  const [isInsideHouse, setIsInsideHouse] = useState(false); // 房子内部状态
  const [houseLevel, setHouseLevel] = useState<'entrance' | 'interior'>('entrance'); // 房子层级状态
  const controlsRef = useRef<any>(null);
  const [keys, setKeys] = useState<{ [key: string]: boolean }>({});
  const moveSpeed = 0.5; // 移动速度

  // 展览馆艺术品数据（窗户、门、靶子等建筑元素）- 立体建筑布局
  const artworks: Artwork[] = [
    // 建筑正面（前方）
     {
      id: 'window1',
      position: [-14, 5, -1.5],
      title: t('sd.artworks.window1.title'),
      author: t('sd.artworks.window1.author'),
      description: t('sd.artworks.window1.description'),
      type: t('sd.artworks.window1.type')
    },
    {
      id: 'door1',
      position: [-14, -3, -2],
      title: t('sd.artworks.door1.title'),
      author: t('sd.artworks.door1.author'),
      description: t('sd.artworks.door1.description'),
      type: t('sd.artworks.door1.type')
    },
    
    // 建筑左侧
    // {
    //   id: 'window2',
    //   position: [3, 2, 0],
    //   title: '现代落地窗',
    //   author: '现代建筑师',
    //   description: '大面积的现代落地窗设计，采用钢化玻璃和铝合金框架。设计简洁现代，提供极佳的采光效果和视野。',
    //   type: '窗户'
    // },
    // {
    //   id: 'door2',
    //   position: [3, 1, 2],
    //   title: '旋转门',
    //   author: '现代设计师',
    //   description: '自动旋转门系统，采用不锈钢和玻璃材质。具有智能感应功能，节能环保，是现代商业建筑的标志性入口设计。',
    //   type: '门'
    // },
    
    // 建筑右侧
   
    // {
    //   id: 'door3',
    //   position: [-3, 1, 2],
    //   title: '防盗门',
    //   author: '安全工程师',
    //   description: '高强度防盗门，采用多层钢板和防盗锁具。门体结构坚固，具有出色的防盗性能。',
    //   type: '门'
    // },
    
    // 建筑背面（后方）
    {
      id: 'window4',
      position: [0, 2, 3],
      title: t('sd.artworks.window4.title'),
      author: t('sd.artworks.window4.author'),
      description: t('sd.artworks.window4.description'),
      type: t('sd.artworks.window4.type')
    },
    {
      id: 'door4',
      position: [-2, 4, -1.5],
      title: t('sd.artworks.door4.title'),
      author: t('sd.artworks.door4.author'),
      description: t('sd.artworks.door4.description'),
      type: t('sd.artworks.door4.type')
    },
    
    // 建筑上层
    {
      id: 'window5',
      position: [0, 4, 0],
      title: t('sd.artworks.window5.title'),
      author: t('sd.artworks.window5.author'),
      description: t('sd.artworks.window5.description'),
      type: t('sd.artworks.window5.type')
    },
    
    // 建筑周围（靶子类）
    {
      id: 'target1',
      position: [-2, -6, 3],
      title: t('sd.artworks.target1.title'),
      author: t('sd.artworks.target1.author'),
      description: t('sd.artworks.target1.description'),
      type: t('sd.artworks.target1.type')
    },
 
    {
      id: 'target3',
      position: [-5, 0, 0],
      title: '移动靶',
      author: '机械工程师',
      description: '可移动的射击靶系统，配备电动轨道和控制系统。靶子可以在轨道上左右移动。',
      type: '靶子'
    },

  ];

  // 建筑内部箭头导航数据
  const navigationArrows: NavigationArrow[] = [
    // 建筑入口区域
    {
      id: 'arrow1',
      position: [-2, -0.1, -1],
      targetPosition: [-2, 2, 2],
      label: t('sd.arrows.enterHall'),
      direction: 'enter',
      distance: t('sd.arrows.distance.forward20')
    },
    {
      id: 'arrow2',
      position: [2, -0.1, -1],
      targetPosition: [2, 2, 2],
      label: t('sd.arrows.enterHall'),
      direction: 'enter',
      distance: t('sd.arrows.distance.forward20')
    },
    
    // 二楼
    {
      id: 'arrow3',
      position: [-3, 2.9, 1],
      targetPosition: [-5, 4, 3],
      label: t('sd.arrows.secondLeft'),
      direction: 'left',
      distance: t('sd.arrows.distance.left15')
    },
    {
      id: 'arrow4',
      position: [3, 2.9, 1],
      targetPosition: [5, 4, 3],
      label: t('sd.arrows.secondRight'),
      direction: 'right',
      distance: t('sd.arrows.distance.right15')
    },
    
    // 三楼
    {
      id: 'arrow5',
      position: [0, 5.9, 3],
      targetPosition: [0, 6, 5],
      label: t('sd.arrows.thirdBack'),
      direction: 'back',
      distance: t('sd.arrows.distance.forward25')
    },
    {
      id: 'arrow6',
      position: [-1, 5.9, 4],
      targetPosition: [-2, 6, 6],
      label: t('sd.arrows.thirdBack'),
      direction: 'back',
      distance: t('sd.arrows.distance.forward25')
    },
    
    // 四楼
    {
      id: 'arrow7',
      position: [0, 8.9, 0],
      targetPosition: [0, 9, 1],
      label: t('sd.arrows.fourthCenter'),
      direction: 'center',
      distance: t('sd.arrows.distance.forward10')
    },
    {
      id: 'arrow8',
      position: [1, 8.9, 0],
      targetPosition: [2, 9, 1],
      label: t('sd.arrows.fourthCenter'),
      direction: 'center',
      distance: t('sd.arrows.distance.forward10')
    },
    
   
    
    // 左边独栋小房子（只有一个入口箭头）
    {
      id: 'arrow11',
      position: [-15, -5, -3],
      targetPosition: [-10, 2, -5],
      label: t('sd.arrows.enterHouse'),
      direction: 'enter',
      distance: t('sd.arrows.distance.forward15'),
      action: 'enterHouse' // 添加进入房子的动作
    },
    
    // 右边独栋房子（3d3.glb模型入口）
    {
      id: 'arrow12',
      position: [15, -5, -3],
      targetPosition: [10, 2, -5],
      label: t('sd.arrows.enterHouse3d3'),
      direction: 'enter',
      distance: t('sd.arrows.distance.forward15'),
      action: 'enterHouse' // 添加进入房子的动作
    }
  ];

  // 键盘控制逻辑
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      setKeys(prev => ({ ...prev, [event.key.toLowerCase()]: true }));
    };

    const handleKeyUp = (event: KeyboardEvent) => {
      setKeys(prev => ({ ...prev, [event.key.toLowerCase()]: false }));
    };

    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, []);

  // 键盘移动逻辑
  useEffect(() => {
    const moveCamera = () => {
      if (!controlsRef.current) return;

      const controls = controlsRef.current;
      const camera = controls.object;
      const target = controls.target;

      // 获取相机的前进方向（朝向目标的方向）
      const direction = new THREE.Vector3();
      direction.subVectors(target, camera.position).normalize();
      
      // 获取相机的右方向（用于左右移动）
      const right = new THREE.Vector3();
      right.crossVectors(direction, camera.up).normalize();

      let moved = false;

      // 前进 (W键 或 上箭头)
      if (keys['w'] || keys['arrowup']) {
        const forward = direction.clone();
        forward.multiplyScalar(moveSpeed);
        camera.position.add(forward);
        target.add(forward);
        moved = true;
      }

      // 后退 (S键 或 下箭头)
      if (keys['s'] || keys['arrowdown']) {
        const backward = direction.clone();
        backward.multiplyScalar(-moveSpeed);
        camera.position.add(backward);
        target.add(backward);
        moved = true;
      }

      // 左移 (A键 或 左箭头)
      if (keys['a'] || keys['arrowleft']) {
        const left = right.clone();
        left.multiplyScalar(-moveSpeed);
        camera.position.add(left);
        target.add(left);
        moved = true;
      }

      // 右移 (D键 或 右箭头)
      if (keys['d'] || keys['arrowright']) {
        const rightMove = right.clone();
        rightMove.multiplyScalar(moveSpeed);
        camera.position.add(rightMove);
        target.add(rightMove);
        moved = true;
      }

      // 上升 (空格键)
      if (keys[' ']) {
        camera.position.y += moveSpeed;
        target.y += moveSpeed;
        moved = true;
      }

      // 下降 (Shift键)
      if (keys['shift']) {
        camera.position.y -= moveSpeed;
        target.y -= moveSpeed;
        moved = true;
      }

      if (moved) {
        controls.update();
      }
    };

    const interval = setInterval(moveCamera, 16); // 60fps
    return () => clearInterval(interval);
  }, [keys, moveSpeed]);

  // 导航到指定位置 - 地面行走模式
  const navigateToPosition = (targetPosition: [number, number, number]) => {
    if (controlsRef.current) {
      // 地面行走模式：保持相机高度，只改变位置
      const controls = controlsRef.current;
      const currentPosition = controls.object.position;
      
      // 计算新的相机位置（保持相同高度）
      const newPosition = new THREE.Vector3(
        targetPosition[0],
        currentPosition.y, // 保持当前高度
        targetPosition[2]
      );
      
      // 平滑移动到新位置
      controls.object.position.copy(newPosition);
      controls.target.set(targetPosition[0], targetPosition[1], targetPosition[2]);
      controls.update();
    }
  };

  // 进入房子内部
  const enterHouse = () => {
    setIsInsideHouse(true);
    setHouseLevel('entrance'); // 重置为入口层级
    // 重置相机位置到房子内部
    if (controlsRef.current) {
      controlsRef.current.object.position.set(0, 2, 5);
      controlsRef.current.target.set(0, 0, 0);
      controlsRef.current.update();
    }
  };

  // 进入房子深层内部
  const enterDeepHouse = () => {
    setHouseLevel('interior');
    // 调整相机位置到深层内部
    if (controlsRef.current) {
      controlsRef.current.object.position.set(0, 1, 3);
      controlsRef.current.target.set(0, 0, 0);
      controlsRef.current.update();
    }
  };

  // 退出房子
  const exitHouse = () => {
    setIsInsideHouse(false);
    setHouseLevel('entrance'); // 重置层级
    // 重置相机位置到外部
    if (controlsRef.current) {
      controlsRef.current.object.position.set(0, 5, 10);
      controlsRef.current.target.set(0, 0, 0);
      controlsRef.current.update();
    }
  };

  // 返回房子入口
  const backToEntrance = () => {
    setHouseLevel('entrance');
    // 调整相机位置回到入口
    if (controlsRef.current) {
      controlsRef.current.object.position.set(0, 2, 5);
      controlsRef.current.target.set(0, 0, 0);
      controlsRef.current.update();
    }
  };

  return (
    <div style={{ width: '100vw', height: '100vh', position: 'relative' }}>
      <Canvas camera={{ position: [0, 5, 10], fov: 60 }}>
        <ambientLight intensity={0.6} />
        <pointLight position={[10, 10, 10]} intensity={1.0} />
        <pointLight position={[-10, 5, -10]} intensity={0.8} />
        <directionalLight position={[0, 10, 0]} intensity={0.5} />
        
        {/* 根据状态显示不同的模型 */}
        {isInsideHouse ? (
          <>
            {houseLevel === 'entrance' ? (
              <>
                <HouseInterior />
                {/* 房子内部导航点 */}
                <HouseInteriorMarker position={[0, 0, -2]} onEnterDeep={enterDeepHouse} />
              </>
            ) : (
              <HouseDeepInterior />
            )}
          </>
        ) : (
          <>
            <ExhibitionHall />
            {artworks.map((art) => (
              <ArtworkMarker key={art.id} artwork={art} onSelect={setSelectedArtwork} />
            ))}
            {navigationArrows.map((arrow) => (
              <NavigationArrow 
                key={arrow.id} 
                arrow={arrow} 
                onNavigate={navigateToPosition} 
                onEnterHouse={enterHouse}
              />
            ))}
          </>
        )}
        
        <OrbitControls 
          ref={controlsRef}
          enableZoom={true} 
          enablePan={true} 
          enableRotate={true}
          minDistance={3}
          maxDistance={30}
          minPolarAngle={0}
          maxPolarAngle={Math.PI}
          target={[0, 0, 0]}
        />
      </Canvas>
      
      <DetailsPanel artwork={selectedArtwork} onClose={() => setSelectedArtwork(null)} />

      {/* 房子导航按钮 */}
      {isInsideHouse && (
        <div style={{ position: 'absolute', top: '20px', left: '20px', zIndex: 2 }}>
          {houseLevel === 'interior' && (
            <button
              onClick={backToEntrance}
              style={{
                background: '#4CAF50',
                color: 'white',
                border: 'none',
                borderRadius: '10px',
                padding: '15px 25px',
                fontSize: '16px',
                fontWeight: 'bold',
                cursor: 'pointer',
                marginRight: '10px',
                boxShadow: '0 4px 8px rgba(0,0,0,0.3)'
              }}
            >
              ↩️ {t('sd.house.backToEntrance')}
            </button>
          )}
          <button
            onClick={exitHouse}
            style={{
              background: '#ff4444',
              color: 'white',
              border: 'none',
              borderRadius: '10px',
              padding: '15px 25px',
              fontSize: '16px',
              fontWeight: 'bold',
              cursor: 'pointer',
              boxShadow: '0 4px 8px rgba(0,0,0,0.3)'
            }}
          >
            🚪 {t('sd.house.exit')}
          </button>
        </div>
      )}

      {/* 控制说明 */}
      <div style={{
        position: 'absolute',
        bottom: '20px',
        left: '20px',
        background: 'rgba(0,0,0,0.8)',
        color: 'white',
        padding: '15px',
        borderRadius: '10px',
        fontSize: '14px',
        zIndex: 1,
        border: '1px solid gold'
      }}>
        <h3 style={{ margin: '0 0 10px 0', color: '#ffd700' }}>
          {isInsideHouse ? '🏠 房子内部控制' : '🏛️ 建筑群键盘+鼠标控制'}
        </h3>
        <ul style={{ margin: 0, paddingLeft: '15px' }}>
          {isInsideHouse ? (
            <>
              <li>🏠 <strong>房子内部浏览：</strong></li>
              <li>🖱️ 左键拖拽：环绕查看</li>
              <li>🔍 滚轮：缩放查看</li>
              <li>🖱️ 右键拖拽：平移移动</li>
              {houseLevel === 'entrance' && <li>🎯 点击导航点：进入房间深处</li>}
              {houseLevel === 'interior' && <li>↩️ 点击返回按钮：回到房子入口</li>}
              <li>🚪 点击退出按钮：退出房子</li>
              <li>🌟 支持360度全方位浏览</li>
            </>
          ) : (
            <>
              <li>⌨️ <strong>键盘控制：</strong></li>
              <li>🔤 W/↑：向前移动</li>
              <li>🔤 S/↓：向后移动</li>
              <li>🔤 A/←：向左移动</li>
              <li>🔤 D/→：向右移动</li>
              <li>🔤 空格：上升</li>
              <li>🔤 Shift：下降</li>
              <li>🖱️ <strong>鼠标控制：</strong></li>
              <li>🖱️ 左键拖拽：环绕展览馆</li>
              <li>🔍 滚轮：缩放查看</li>
              <li>🖱️ 右键拖拽：平移移动</li>
              <li>🎯 点击红色标记：查看艺术品详情</li>
              <li>➤ 点击小箭头：楼层导航</li>
              <li>🏠 点击房子图标：进入房子内部</li>
              <li>🪟 窗户类：2个展品</li>
              <li>🚪 门类：2个展品</li>
              <li>🎯 靶子类：2个展品</li>
              <li>🌟 支持360度全方位浏览</li>
              <li>📍 建筑群导航：主楼5层+小房子入口</li>
            </>
          )}
        </ul>
      </div>
    </div>
  );
}

export default Sd;
